import 'package:azlistview_plus/azlistview_plus.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:get/get.dart';
import 'package:life_service/color/hex.dart';
import 'package:life_service/extensions/ex_widget.dart';
import 'package:life_service/model/city.dart';
import 'package:life_service/ui/draw_under_line.dart';
import 'package:life_service/utils/styles.dart';

import 'controller.dart';

class SelectCityPage extends GetView<SelectCityController> {
  const SelectCityPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        leading: IconButton(
          onPressed: Get.back,
          icon: Icon(
            CupertinoIcons.chevron_back,
            size: 20,
            color: HexColor(HexColor.color3333),
          ),
        ),
        backgroundColor: Colors.white,
        title: TextField(
          style: StylesUtils.customTextStyle(
            color: HexColor.color3333,
          ),
          decoration: InputDecoration(
            constraints: const BoxConstraints.expand(width: 290, height: 36),
            prefixIconConstraints:
                const BoxConstraints.expand(width: 40, height: 36),
            prefixIcon: IconButton(
              onPressed: () {},
              icon: Icon(
                CupertinoIcons.search,
                size: 18,
                color: HexColor(HexColor.color9999),
              ),
            ),
            suffixIconConstraints:
                const BoxConstraints.expand(width: 40, height: 36),
            suffixIcon: IconButton(
              onPressed: () {
                controller.focusNode.unfocus();
                controller.textEditingController.text = '';
                // FocusManager.instance.primaryFocus?.unfocus();
                controller.isShowSearch.value = false;
              },
              icon: Icon(
                CupertinoIcons.xmark_circle_fill,
                size: 16,
                color: HexColor(HexColor.color9999),
              ),
            ),
            filled: true,
            fillColor: HexColor(HexColor.colorF7f7),
            hintText: '城市/区域/位置',
            hintStyle: StylesUtils.customTextStyle(
              color: HexColor.color9999,
              fontSize: StylesUtils.fontSize13,
            ),
            focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
                borderSide: BorderSide.none),
            border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
                borderSide: BorderSide.none),
            enabledBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
                borderSide: BorderSide.none),
            isCollapsed: true,
            isDense: true,
            contentPadding: const EdgeInsets.only(top: 12, left: 15),
          ),
          onSubmitted: (String keyword) {},
          onChanged: (String query) {},
          onTap: () {
            controller.isShowSearch.value = true;
            // Navigator.push(
            //   context,
            //   PageRouteBuilder(
            //     transitionDuration: const Duration(milliseconds: 300),
            //     pageBuilder: (context, _, __) => Container(
            //       color: Colors.red,
            //     ),
            //     transitionsBuilder:
            //         (_, Animation<double> animation, __, Widget child) =>
            //             SlideTransition(
            //       position: Tween<Offset>(
            //         begin: const Offset(0.0, 1.0),
            //         end: const Offset(0.0, 0.0),
            //       ).animate(animation),
            //       child: child,
            //     ),
            //   ),
            // );
          },
          controller: controller.textEditingController,
          textInputAction: TextInputAction.search,
          focusNode: controller.focusNode,
          onTapOutside: (event) {
            controller.focusNode.unfocus();
          },
        ),
        actions: [
          TextButton(
            onPressed: () {},
            child: Text(
              '取消',
              style: StylesUtils.customTextStyle(
                color: HexColor.color9999,
              ),
            ),
          ),
        ],
      ),
      body: Stack(
        children: [
          Obx(
            () => AzListView(
              data: controller.cityList,
              itemCount: controller.cityList.length,
              itemBuilder: (BuildContext context, int index) {
                if (index == 0) return buildHeader();
                CityModel model = controller.cityList[index];
                return getListItem(context, model,
                    susHeight: controller.susItemHeight);
              },
              susPosition: Offset.zero,
              susItemHeight: controller.susItemHeight,
              susItemBuilder: (BuildContext context, int index) {
                CityModel model = controller.cityList[index];
                String tag = model.getSuspensionTag();
                if (controller.imgFavorite == tag) {
                  return Container();
                }
                return getSusItem(context, tag,
                    susHeight: controller.susItemHeight);
              },
              indexBarData: SuspensionUtil.getTagIndexList(controller.cityList),
              indexBarOptions: IndexBarOptions(
                needRebuild: true,
                color: Colors.transparent,
                downColor: const Color(0xFFEEEEEE),
                localImages: [controller.imgFavorite], //local images.
              ),
            ),
          ),
          Obx(
            () => AnimatedPositioned(
              left: 0,
              right: 0,
              bottom: 0,
              top: controller.isShowSearch.isTrue ? 0 : Get.height,
              duration: const Duration(milliseconds: 300),
              curve: Curves.linear,
              child: Container(
                padding: EdgeInsets.only(left: (Get.width - 356) / 2),
                color: Colors.white,
                child: ListView.builder(
                  itemBuilder: (c, i) {
                    return CustomPaint(
                      painter: _DrawLinePainter(),
                      child: Padding(
                        padding: const EdgeInsets.symmetric(vertical: 6),
                        child: Stack(
                          children: [
                            Column(
                              children: [
                                Container(
                                  height: 24,
                                  alignment: Alignment.centerLeft,
                                  child: Text(
                                    '北海',
                                    style: StylesUtils.customTextStyle(
                                      fontSize: StylesUtils.fontSize15,
                                      color: HexColor.color3333,
                                    ),
                                  ),
                                ),
                                Container(
                                  height: 24,
                                  alignment: Alignment.centerLeft,
                                  child: Text(
                                    '广西-北海',
                                    style: StylesUtils.customTextStyle(
                                      fontSize: StylesUtils.fontSize13,
                                      color: HexColor.color6666,
                                    ),
                                  ),
                                )
                              ],
                            ),
                            Positioned(
                              top: 0,
                              right: 30,
                              bottom: 0,
                              child: Center(
                                child: Text(
                                  '酒店',
                                  style: StylesUtils.customTextStyle(
                                    fontSize: StylesUtils.fontSize13,
                                    color: HexColor.color3333,
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    );
                  },
                  itemCount: 5,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  void showSnackBar(BuildContext context, String msg) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(msg),
        duration: const Duration(seconds: 2),
      ),
    );
  }

  Widget getSusItem(BuildContext context, String tag, {double susHeight = 40}) {
    return Container(
      height: susHeight,
      width: Get.width,
      padding: const EdgeInsets.only(left: 20),
      color: const Color(0xFFF3F4F5),
      alignment: Alignment.centerLeft,
      child: Text(
        tag,
        style: const TextStyle(
          fontSize: 14.0,
          color: Color(0xFF666666),
        ),
      ),
    );
  }

  Widget getListItem(BuildContext context, CityModel model,
      {double susHeight = 40}) {
    return DrawUnderLine(
      dx: 20,
      child: Container(
        alignment: Alignment.centerLeft,
        height: susHeight,
        padding: const EdgeInsets.only(left: 20),
        child: Text(
          model.name,
          style: StylesUtils.customTextStyle(
            color: HexColor.color3333,
            fontSize: StylesUtils.fontSize13,
          ),
        ),
      ),
    ).onTap(() {
      showSnackBar(context, 'onItemClick : ${model.name}');
    });
  }

  Widget buildHeader() {
    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.only(bottom: 15),
          child: CustomPaint(
            painter: _MyDrawLinePainter(),
            child: Container(
              height: 20,
              padding: const EdgeInsets.only(left: 15),
              alignment: Alignment.centerLeft,
              child: Text(
                '当前/历史',
                style: StylesUtils.customTextStyle(
                  fontSize: StylesUtils.fontSize16,
                  color: HexColor.color3333,
                  fontWeight: FontWeight.w700,
                ),
              ),
            ),
          ),
        ),
        StaggeredGrid.count(
          crossAxisCount: 3,
          crossAxisSpacing: 10,
          children: [
            Container(
              height: 30,
              decoration: BoxDecoration(
                color: HexColor.rgba(255, 98, 98, 0.0980392156862745),
                borderRadius: BorderRadius.circular(4),
              ),
              alignment: Alignment.center,
              child: Text.rich(
                TextSpan(
                  children: [
                    WidgetSpan(
                        child: Icon(
                          CupertinoIcons.placemark_fill,
                          size: 16,
                          color: HexColor(HexColor.colorFf00),
                        ),
                        alignment: PlaceholderAlignment.middle),
                    TextSpan(
                      text: '  北海',
                      style: StylesUtils.customTextStyle(
                          fontSize: StylesUtils.fontSize13,
                          color: HexColor.colorFf00),
                    )
                  ],
                ),
              ),
            ),
            Container(
              height: 30,
              decoration: BoxDecoration(
                color: HexColor.rgba(255, 98, 98, 0.0980392156862745),
                borderRadius: BorderRadius.circular(4),
              ),
              alignment: Alignment.center,
              child: Text(
                '钦州',
                style: StylesUtils.customTextStyle(
                    fontSize: StylesUtils.fontSize13,
                    color: HexColor.color3333),
              ),
            ),
            Container(
              height: 30,
              decoration: BoxDecoration(
                color: HexColor.rgba(255, 98, 98, 0.0980392156862745),
                borderRadius: BorderRadius.circular(4),
              ),
              alignment: Alignment.center,
              child: Text(
                '南宁',
                style: StylesUtils.customTextStyle(
                    fontSize: StylesUtils.fontSize13,
                    color: HexColor.color3333),
              ),
            ),
          ],
        ).paddingOnly(right: 15),
        Padding(
          padding: const EdgeInsets.only(top: 15, bottom: 15),
          child: CustomPaint(
            painter: _MyDrawLinePainter(),
            child: Container(
              height: 20,
              padding: const EdgeInsets.only(left: 15),
              alignment: Alignment.centerLeft,
              child: Text(
                '热门城市',
                style: StylesUtils.customTextStyle(
                  fontSize: StylesUtils.fontSize16,
                  color: HexColor.color3333,
                  fontWeight: FontWeight.w700,
                ),
              ),
            ),
          ),
        ),
        StaggeredGrid.count(
          crossAxisCount: 3,
          crossAxisSpacing: 10,
          mainAxisSpacing: 10,
          children: [
            for (var i = 0; i < 9; i++)
              Container(
                height: 30,
                decoration: BoxDecoration(
                  color: HexColor.rgba(255, 98, 98, 0.0980392156862745),
                  borderRadius: BorderRadius.circular(4),
                ),
                alignment: Alignment.center,
                child: Text(
                  '杭州',
                  style: StylesUtils.customTextStyle(
                      fontSize: StylesUtils.fontSize13,
                      color: HexColor.color3333),
                ),
              ),
          ],
        ).paddingOnly(right: 15).paddingOnly(bottom: 15),
      ],
    ).padding(
      value: const EdgeInsets.only(left: 20, right: 10),
    );
  }
}

class _MyDrawLinePainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()
      ..strokeWidth = 5
      ..color = HexColor(HexColor.colorFf62)
      ..strokeCap = StrokeCap.round
      ..style = PaintingStyle.fill;
    RRect rrect = RRect.fromRectAndRadius(
        Rect.fromLTWH(0, 0, 5, size.height), const Radius.circular(2));
    canvas.drawRRect(rrect, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return this != oldDelegate;
  }
}

class _DrawLinePainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()
      ..strokeWidth = 1
      ..color = HexColor(HexColor.colorF2f2)
      ..strokeCap = StrokeCap.round
      ..style = PaintingStyle.stroke;

    canvas.drawLine(
        Offset(0, size.height), Offset(size.width, size.height), paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return this != oldDelegate;
  }
}
